
import store from '../store'
import routes from './routes'
import routeUtil from '../core/route-interceptor'

import { loginRouteName, exceptionRoutesName } from '../env'

// 路由名白名单
const whiteNameList = [loginRouteName]

const run = (router) => {
  router.beforeEach((to, from, next) => {
    if (whiteNameList.includes(to.name)) {
      return next()
    }
    // 检查是否已授权
    if (!store.state.user.isAuthenticated) {
      store.dispatch('user/doGetAuthInfo').then(() => {
        store.dispatch('user/doGetUserInfo').then(() => {
          next({ ...to, replace: true })
        }).catch(() => {
          next({ name: loginRouteName })
        })
      }).catch(() => {
        next({ name: loginRouteName })
      })
    } else {
      if (store.getters['isSuper']) {
        return next()
      }
      if (routeUtil.canJump(to, routes, store.getters['permissions'])) {
        next()
      } else {
        next({
          name: exceptionRoutesName.NoAuth
        })
      }
    }
  })

  router.afterEach((to, from) => {
  })
}

export default {
  run
}
